package arrAndstr;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

/*
    102. 二叉树的层序遍历
 */
public class T102 {

   public class TreeNode {
       int val;
       TreeNode left;
       TreeNode right;
       TreeNode() {}
       TreeNode(int val) { this.val = val; }
       TreeNode(int val, TreeNode left, TreeNode right) {
           this.val = val;
           this.left = left;
           this.right = right;
       }
   }


    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if (root == null)   return result;

        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            List<Integer> list = new ArrayList<>();
            int num = queue.size();

            for (int i = 0; i < num; i++) {
                TreeNode node = queue.poll();
                list.add(node.val);

                if (node.left != null)  queue.add(node.left);
                if (node.right != null)  queue.add(node.right);
            }
            result.add(list);
        }

        return result;
    }
}
